<?php
/**
 *
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-08 14:55:37
 * @version $Id$
 */
namespace app\agent\controller;

use think\Config;
use think\Db;
use think\Session;
use think\Controller;
use Payinterface\PaySdk;
use think\Log;

class Order extends Shopbase
{
    public $error = [];
    //用户订单列表
    function index()
    {
        $uid = $this->shop_uid;
        $params = Request()->param();
        $query = Db::table('sdzx_order')->alias('o')
        ->join('sdzx_order_goods g', 'o.order_id=g.order_id')
        ->where("o.order_status > -1 and o.user_id={$uid}")
        ->order('o.create_time desc');
        if (isset($params['status'])) {
            switch ($params['status']) {
                case 'all':
                    # 所有订单
                    break;
                case '1':
                    # 待支付
                    $query->where("o.order_status=0");
                    break;
                case '2':
                    # 待发货
                    $query->where("o.order_status=30 or o.order_status=20");
                    break;
                case '3':
                    # 待收货
                    $query->where("o.order_status=40");
                    break;
                case '4':
                    # 待评价
                    $query->where("o.order_status=100 and o.is_evaluate=0");
                    break;
                default:
                    # 默认只查出未完成的订单
                    // $query->where("o.order_status >= 0 and o.order_status < 100");
                    break;
            }
        }

        $page = isset($params['page'])?$params['page']:1;
        $list = $query->select();
        // 订单合并
        $tmp_arr=[];
        foreach ($list as $k => $v) {
            if (!isset($tmp_arr[$v['order_id']])) {
                $order = [
                    'order_id'          => $v['order_id'],
                    'order_no'          => $v['order_no'],
                    'order_type'        => $v['order_type'],  //订单类型1：自主下单 2：代下单
                    'payment_type'      => $v['payment_type'], //支付类型  1：自主支付 2：管家支付
                    'user_id'           => $v['user_id'],
                    'user_name'         => $v['user_name'],
                    'agent_id'          => $v['agent_id'], //管家ID订单类型为 代下单 是才有
                    'agent_name'        => $v['agent_name'],
                    'create_time'       => $v['create_time'],
                    'receiver_name'     => $v['receiver_name'],
                    'receiver_mobile'   => $v['receiver_mobile'],
                    // 'receiver_province' => $v['receiver_province'],
                    // 'receiver_city'     => $v['receiver_city'],
                    // 'receiver_district' => $v['receiver_district'],
                    'receiver_address'  => $v['receiver_address'],
                    'receiver_pcd'      => $v['receiver_pcd'],
                    'goods_money'       => $v['goods_money'],
                    'order_money'       => $v['order_money'],
                    'coupon_money'      => $v['coupon_money'],
                    'coupon_id'         => $v['coupon_id'],
                    'user_money'        => $v['user_money'],
                    'shipping_money'    => $v['shipping_money'],
                    'order_status'      => $v['order_status'],
                    'pay_platform'      => $v['pay_platform'],
                ];
                $tmp_arr[$v['order_id']] = $order;
            }
            $tmp_arr[$v['order_id']]['list'][] = $v;
        }
        //分类统计
        $statusNum=['all'=>0];
        $return_arr=[];
        foreach ($tmp_arr as $k => $v) {
            if (isset($statusNum[$v['order_status']])) {
                $statusNum[$v['order_status']]++;
            } else {
                $statusNum[$v['order_status']]=1;
            }
            $statusNum['all']++;
            $return_arr[] = $v;
        }
        // p($return_arr);
        return $this->fetch('',['list'=>$return_arr,'statusNum'=>$statusNum]);
        
    }

    /**
     * 判断今天配送还是明天配送
     * @return [type] [description]
     */
    function scheduling()
    {
        if (isset($data['scheduling']) && $data['scheduling']==1) { //用户指定明天送
            $this->error('您选择了次日配送（'.date('Y-m-d', strtotime('+1 day')).'）','');
        } elseif (Config::get('sites.scheduling')) {
            $scheduling_time = strtotime(Config::get('sites.scheduling'));
            if (time()<=$scheduling_time) {
                $this->success('今天','');
            } else {
                $this->error(Config::get('sites.scheduling').' 后下单将为客户次日配送（'.date('Y-m-d', strtotime('+1 day')).'）','');
            }
        } else {
            $this->success('今天','');
        }
    }
    /**
     * 下单
     */
    function add()
    {
        $uid = $this->shop_uid;
        //{specval_id:23_2,25_2,28_2,address_id:14}
        $data = Request()->param();
        !isset($data['specval_id']) && $this->error('未选择商品');
        !isset($data['address_id']) && $this->error('未选择收获地址');
        $data['specval_id'] = explode(',', $data['specval_id']);

        //通过规格ID 查出商品
        $goods = [];
        foreach ($data['specval_id'] as $k => $v) {
            $id_num = explode('_', $v);
            if ($id_num[1]<=0) { continue; }
            $tmp = Db::connect([], 'goods')->field('g.*,sval.*,s.supplier_id,s.supplier_name,b.brand_id,b.brand_name')
            ->table('sdzx_goods')->alias('g')
            ->join('sdzx_goods_specval sval', 'g.goods_id=sval.goods_id')
            ->join('sdzx_goods_brand b', 'g.brand_id=b.brand_id', 'left')
            ->join('sdzx_supplier s', 'sval.supplier_id=s.supplier_id', 'left')
            ->where("sval.specval_id={$id_num[0]}")
            ->find();
            $tmp['num'] = $id_num[1];
            $goods[] = $tmp;
        }
        if (empty($goods)) {
            $this->error('未选择商品');
        }

        $order_money = 0; //订单总价
        //查商品活动价格
        # ToDo
        
        //金券支付金额
        # ToDo
        $coupon_id=0;
        $coupon_money=0;
        if (isset($data['coupon_id'])) {
            # code...
        }

        //计算商品价格
        $goods_money=0;
        $total_cost_price=0;
        foreach ($goods as $k => $v) {
            $goods_money += $v['price']*$v['num'];
            $total_cost_price += $v['cost_price']*$v['num'];
        }
        $order_money += $goods_money;

        //订单运费
        $shipping_money = $this->shippingMoney($order_money);
        $order_money += $shipping_money['delivery_fee'];
        
         //如果用户使用余额使用
         $user_money=0;
        if (isset($data['user_money'])) {
            # code...
        }
        
        

        //收货地址
        $address = Db::name('user_address')->where(['address_id'=>$data['address_id'],'user_id'=>$uid])->find();
        !$address && $this->error('收获地址错误');

        $time = date('Y-m-d H:i:s');
        $order = [
            'order_no'         => $this->orderSn(),
            'order_type'       => 2,  //订单类型1：自主下单 2：代下单
            'payment_type'     => 1, //支付类型  1：自主支付 2：管家支付
            'user_id'          => $uid,
            'user_name'        => $this->shop_user['realname'],
            'openid'           => $this->shop_user['openid'],
            'agent_id'         => $this->uid, //管家ID订单类型为 代下单 是才有
            'agent_name'       => $this->user['name'],
            'create_time'      => $time,
            'receiver_name'    => $address['name'], //收货人姓名
            'receiver_mobile'  => $address['phone'],

            'receiver_address' => $address['address'],
            'receiver_pcd'     => $address['pcd'],
            'goods_money'      => $goods_money, //商品总价
            'order_money'      => $order_money, //订单总价
            'coupon_money'     => $coupon_money, //订单代金券支付金额
            'coupon_id'        => $coupon_id,
            'user_money'       => $user_money, //订单余额支付金额
            'shipping_money'   => $shipping_money['delivery_fee'], //订单运费
            'order_status'     => 0,
            'remarks'          => $data['remarks'],
        ];

        //配送时间
        if (isset($data['scheduling']) && $data['scheduling']==1) { //用户指定明天送
            $order['scheduling'] = date('Y-m-d', strtotime('+1 day'));
        } elseif (Config::get('sites.scheduling')) {
            $scheduling_time = strtotime(Config::get('sites.scheduling'));
            if (time()<=$scheduling_time) {
                $order['scheduling'] = date('Y-m-d');
            } else {
                $order['scheduling'] = date('Y-m-d', strtotime('+1 day'));
            }
        } else {
            $order['scheduling'] = date('Y-m-d');
        }

        Db::startTrans();
        $order_id = Db::name('order')->insertGetId($order);

        if (!$order_id) {
            Db::rollback();
            $this->error('订单保存失败');
        }
        $order_goods=[];
        foreach ($goods as $key => $value) {
            $order_goods[] = [
                'order_id'           => $order_id,
                'goods_name'         => $value['goods_name'],
                'goods_id'           => $value['goods_id'],
                'goods_spec_id'      => $value['spec_id'],
                'goods_spec_name'    => $value['spec_name'],
                'goods_specval_id'   => $value['specval_id'],
                'goods_specval_name' => $value['specval_name'],
                'supplier_name'      => $value['supplier_name'],
                'supplier_id'        => $value['supplier_id'],
                'price'              => $value['price'],
                'cost_price'         => $value['cost_price'],
                'num'                => $value['num'],
                'goods_picture'      => $value['picture'],
                'brand_id'           => $value['brand_id'],
                'brand_name'         => $value['brand_name'],
            ];
        }
        $re_order_goods = Db::name('order_goods')->insertAll($order_goods);
        if (!$re_order_goods) {
            Db::rollback();
            $this->error('订单保存失败');
        }

        //查看订单号是否存在  存在则是错的
        $isset = Db::name('order_prepay')->where(['order_no'=>$order['order_no']])->find();
        $isset && $this->error('下单失败，请重新提交订单');

        Db::name('order_action')->insert([
            'user_id'          => $uid,
            'order_id'         => $order_id,
            'act_time'         => $time,
            'order_status'     => 0,
            'bop_order_status' => 0
        ]);

        // 清除购物车数据
        Db::name('user_cart')->where(['specval_id'=>['in',$data['specval_id']],'user_id'=>$uid])->delete();

        Db::commit();
        self::sendTmp($order);
        $parameters['order_id'] = $order_id;
        $this->success('下单成功，并已通知商户付款', '', ['parameters'=>$parameters]);

    }

    /**
     * 代支付
     */
    function pay()
    {
        $uid = $this->shop_uid;
        //{specval_id:23_2,25_2,28_2,address_id:14}
        $data = Request()->param();
        !isset($data['specval_id']) && $this->error('未选择商品');
        !isset($data['address_id']) && $this->error('未选择收获地址');
        $data['specval_id'] = explode(',', $data['specval_id']);

        //通过规格ID 查出商品
        $goods = [];
        foreach ($data['specval_id'] as $k => $v) {
            $id_num = explode('_', $v);
            if ($id_num[1]<=0) { continue; }
            $tmp = Db::connect([], 'goods')->field('g.*,sval.*,s.supplier_id,s.supplier_name,b.brand_id,b.brand_name')
            ->table('sdzx_goods')->alias('g')
            ->join('sdzx_goods_specval sval', 'g.goods_id=sval.goods_id')
            ->join('sdzx_goods_brand b', 'g.brand_id=b.brand_id', 'left')
            ->join('sdzx_supplier s', 'sval.supplier_id=s.supplier_id', 'left')
            ->where("sval.specval_id={$id_num[0]}")
            ->find();
            $tmp['num'] = $id_num[1];
            $goods[] = $tmp;
        }
        if (empty($goods)) {
            $this->error('未选择商品');
        }

        $order_money = 0; //订单总价
        //查商品活动价格
        # ToDo
        
        //金券支付金额
        # ToDo
        $coupon_id=0;
        $coupon_money=0;
        if (isset($data['coupon_id'])) {
            # code...
        }

        //计算商品价格
        $goods_money=0;
        $total_cost_price=0;
        foreach ($goods as $k => $v) {
            $goods_money += $v['price']*$v['num'];
            $total_cost_price += $v['cost_price']*$v['num'];
        }
        $order_money += $goods_money;

        //订单运费
        $shipping_money = $this->shippingMoney($order_money);
        $order_money += $shipping_money['delivery_fee'];
        
         //如果用户使用余额使用
         $user_money=0;
        if (isset($data['user_money'])) {
            # code...
        }
        
        

        //收货地址
        $address = Db::name('user_address')->where(['address_id'=>$data['address_id'],'user_id'=>$uid])->find();
        !$address && $this->error('收获地址错误');

        $time = date('Y-m-d H:i:s');
        $order = [
            'order_no'          => $this->orderSn(),
            'order_type'        => 2,  //订单类型1：自主下单 2：代下单
            'payment_type'      => 2, //支付类型  1：自主支付 2：管家支付
            'user_id'           => $uid,
            'user_name'         => $this->shop_user['realname'],
            'openid'            => $this->shop_user['openid'],
            'agent_id'          => $this->uid, //管家ID订单类型为 代下单 是才有
            'agent_name'        => $this->user['name'],
            'create_time'       => $time,
            'receiver_name'     => $address['name'], //收货人姓名
            'receiver_mobile'   => $address['phone'],
            'receiver_address'  => $address['address'],
            'receiver_pcd'      => $address['pcd'],
            'goods_money'       => $goods_money, //商品总价
            'order_money'       => $order_money, //订单总价
            'coupon_money'      => $coupon_money, //订单代金券支付金额
            'coupon_id'         => $coupon_id,
            'user_money'        => $user_money, //订单余额支付金额
            'shipping_money'    => $shipping_money['delivery_fee'], //订单运费
            'order_status'      => 0,
            'remarks'           => $data['remarks'],
        ];

        //配送时间
        if (isset($data['scheduling']) && $data['scheduling']==1) { //用户指定明天送
            $order['scheduling'] = date('Y-m-d', strtotime('+1 day'));
        } elseif (Config::get('sites.scheduling')) {
            $scheduling_time = strtotime(Config::get('sites.scheduling'));
            if (time()<=$scheduling_time) {
                $order['scheduling'] = date('Y-m-d');
            } else {
                $order['scheduling'] = date('Y-m-d', strtotime('+1 day'));
            }
        } else {
            $order['scheduling'] = date('Y-m-d');
        }

        Db::startTrans();
        $order_id = Db::name('order')->insertGetId($order);

        if (!$order_id) {
            Db::rollback();
            $this->error('订单保存失败');
        }
        $order_goods=[];
        foreach ($goods as $key => $value) {
            $order_goods[] = [
                'order_id'           => $order_id,
                'goods_name'         => $value['goods_name'],
                'goods_id'           => $value['goods_id'],
                'goods_spec_id'      => $value['spec_id'],
                'goods_spec_name'    => $value['spec_name'],
                'goods_specval_id'   => $value['specval_id'],
                'goods_specval_name' => $value['specval_name'],
                'supplier_name'      => $value['supplier_name'],
                'supplier_id'        => $value['supplier_id'],
                'price'              => $value['price'],
                'cost_price'         => $value['cost_price'],
                'num'                => $value['num'],
                'goods_picture'      => $value['picture'],
                'brand_id'           => $value['brand_id'],
                'brand_name'         => $value['brand_name'],
            ];
        }
        $re_order_goods = Db::name('order_goods')->insertAll($order_goods);
        if (!$re_order_goods) {
            Db::rollback();
            $this->error('订单保存失败');
        }

        //查看订单号是否存在  存在则是错的
        $isset = Db::name('order_prepay')->where(['order_no'=>$order['order_no']])->find();
        $isset && $this->error('下单失败，请重新提交订单');

        //支付中间表 避免订单号重复
        $prepay_date['out_trade_no'] = $order_id.time();
        $order['out_trade_no'] = $prepay_date['out_trade_no'];

        // 生成支付参数
        $order['order_id']   = $order_id;
        $order['time_start'] = $time;
        $order['body']       = Config::get('site.title');

        $pay = $this->wxPay($order);
        if ($pay['status']) {
            // 清除购物车数据
            Db::name('user_cart')->where(['specval_id'=>['in',$data['specval_id']],'user_id'=>$uid])->delete();

            $prepay_date['order_no']     = $order['order_no'];
            $prepay_date['order_id']     = $order['order_id'];
            $prepay_date['out_trade_no'] = $order['out_trade_no'];
            $prepay_date['body']         = $order['body'];

            $prepay_date['total_fee']    = $order['order_money']*100;
            $prepay_date['time_start']   = $order['time_start'];
            $prepay_date['trade_type']   = 'WAP';
            $prepay_date['parameters']   = json_encode($pay['data']);
            $prepay_date['payment_type'] = 2;
            
            if (isset($order['time_expire'])) {
                $prepay_date['time_expire'] = $order['time_expire'];
            }
            if (isset($order['goods_tag'])) {
                $prepay_date['goods_tag'] = $order['goods_tag'];
            }

            Db::name('order_prepay')->insert($prepay_date);

            Db::name('order_action')->insert([
                'user_id'          => $uid,
                'order_id'         => $order_id,
                'act_time'         => $time,
                'order_status'     => 0,
                'bop_order_status' => 0,
                'act_remark' => '您的订单已被管家支付,等待系统确认。'
            ]);

            Db::commit();
            // self::sendTmp($order);
            // $this->success('下单成功，并已通知商户付款', '', ['mweb_url'=>$mweb_url]);
            
            $this->success('订单提交成功，请在微信中完成支付', '', ['parameters'=>$pay['data']]);
        } else {
            Db::rollback();
            $this->error('支付错误', '', $pay['msg']);
        }
    }

    /**
     * 历史订单支付
     * @return [type] [description]
     */
    function rePay()
    {
        $orderID = Request()->param('order_id');
        !$orderID && $this->error('参数错误');
        $time = date('Y-m-d H:i:s');
        $order = Db::name('order')->where(['order_id'=>$orderID])->find();

        $time_expire = date('Y-m-d H:i:s', strtotime('-1 hours'));

        if ($order['order_status']==25) { //补差价
            $change_price = Db::name('order_change')->where(['order_id'=>$orderID])->order('change_id desc')->find();
            //先看之前的prepay_id 有没有过期(有效期 2 小时)
            $prepay = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>1,'status'=>0])->find();
            $usefull = false;
            if ($prepay['time_start'] > $time_expire) {
                $usefull = true;
            }

            if ($prepay['payment_type'] != 2) {
                $usefull = false;
            }

            if (empty($prepay['parameters'])) {
                $usefull = false;
            }

            if ($prepay['time_expire'] !=0 && $time > $prepay['time_expire']) {
                $usefull = false;
            }

            if ($prepay['total_fee'] != 100*$change_price['price']) {
                $usefull = false;
            }

            if ($usefull) {
                $this->success('下单成功', '', ['parameters'=>json_decode($prepay['parameters'], true)]);
            } else {
                //支付中间表 避免订单号重复
                $prepay_date['out_trade_no']  = $order['order_id'].time();
                $change_order['out_trade_no'] = $prepay_date['out_trade_no'];
                $change_order['order_no']     = $order['order_no'];
                $change_order['order_id']     = $order['order_id'];
                $change_order['time_start']   = $time;
                $change_order['body']         = Config::get('site.title').'订单补价';
                // $change_order['detail']       = '';
                $change_order['order_money']  = $change_price['price'];

                $parameters = $this->wxPay($change_order);
                if ($parameters['status']) {
                    $prepay_date['parameters']   = json_encode($parameters['data']);
                   
                    $prepay_date['order_no']     = $change_order['order_no'];
                    $prepay_date['order_id']     = $change_order['order_id'];
                    $prepay_date['body']         = $change_order['body'];
                    // $prepay_date['detail']       = $change_order['detail'];
                    $prepay_date['total_fee']    = $change_order['order_money']*100;
                    $prepay_date['time_start']   = $time;
                    $prepay_date['trade_type']   = 'WAP';
                    // $prepay_date['prepay_id']    = $prepay_id;
                    $prepay_date['prepay_type']  = 1;
                    $prepay_date['payment_type'] = 2;

                    // 查看是否存在 prepay
                    $isset = Db::name('order_prepay')->where(['order_id'=>$change_order['order_id'],'prepay_type'=>1,'status'=>0])->find();
                    if ($isset) {
                        Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>1,'status'=>0])->update($prepay_date);
                    } else {
                        Db::name('order_prepay')->insert($prepay_date);
                    }

                    $this->success('下单成功', '', ['parameters'=>$parameters['data']]);
                }
            }
            $this->error('支付错误', '');
        }

        //先看之前的prepay_id 有没有过期(有效期 2 小时)
        $prepay = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>0])->find();
        $usefull = false;
        if ($prepay['time_start'] > $time_expire) {
            $usefull = true;
        }

        if (empty($prepay['parameters'])) {
            $usefull = false;
        }

        if ($prepay['time_expire'] !=0 && $time > $prepay['time_expire']) {
            $usefull = false;
        }

        if ($prepay['total_fee'] != $order['order_money']*100) {
            $usefull = false;
        }

        if ($usefull) {
            $this->success('下单成功', '', ['parameters'=>json_decode($prepay['parameters'], true)]);
            
        } else {
            //支付中间表 避免订单号重复
            $prepay_date['out_trade_no'] = $order['order_id'].time();
            $order['out_trade_no'] = $prepay_date['out_trade_no'];

            // 生成支付参数
            $order['time_start'] = $time;
            $order['body']       = Config::get('site.title');

            $parameters = $this->wxPay($order);
            if ($parameters['status']) {
                $prepay_date['parameters']   = json_encode($parameters['data']);
                
                $prepay_date['order_no']     = $order['order_no'];
                $prepay_date['order_id']     = $order['order_id'];
                $prepay_date['out_trade_no'] = $order['out_trade_no'];
                $prepay_date['body']         = $order['body'];
                $prepay_date['total_fee']    = $order['order_money']*100;
                $prepay_date['time_start']   = $order['time_start'];
                $prepay_date['trade_type']   = 'WAP';
                // $prepay_date['prepay_id']    = $prepay_id;
                $prepay_date['prepay_type']  = 0;

                if (isset($order['time_expire'])) {
                    $prepay_date['time_expire'] = $order['time_expire'];
                }
                if (isset($order['goods_tag'])) {
                    $prepay_date['goods_tag'] = $order['goods_tag'];
                }

                // 查看是否存在 prepay
                $isset = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>0])->find();
                if ($isset) {
                    Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>0])->update($prepay_date);
                } else {
                    Db::name('order_prepay')->insert($prepay_date);
                }

                $this->success('下单成功', '', ['parameters'=>$parameters['data']]);
            } else {
                $this->error('支付错误', '', $this->error);
            }
        }
    }

    /**
     * 发送模板消息
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    function sendTmp($order){
        import('Alidayu.TopSdk');
        import('Alidayu.top.TopClient');
        import('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
        $appkey="23535194";
        $secret="48953173553ad6ad6b306138f518d7f1";


        $code=substr(str_shuffle("012345678901234567890123456789"), 0, 6);
        $product="速冻在线";

        $c = new \TopClient();
        $c ->appkey = $appkey ;
        $c ->secretKey = $secret ;
        $req = new \AlibabaAliqinFcSmsNumSendRequest();
        $req ->setExtend( "" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "速冻在线" );
        $req ->setSmsParam("{name:'".$order['receiver_name']."',order:'".$order['order_no']."',price:'".$order['order_money']."'}");
        $req ->setRecNum( $order['receiver_mobile'] );
        $req ->setSmsTemplateCode( "SMS_94720061" );
        $re = $c ->execute( $req );
    }

    /**
     * 生成订单号
     * @return [type] [description]
     */
    function orderSn()
    {
        $u = strrev(sprintf('%04s', substr($this->shop_uid, -4)));
        $sn = $u.date('ymdHi').sprintf('%02s', rand(0, 99));
        return $sn;
    }

    /**
     * 删除订单
     * @return [type] [description]
     */
    function del()
    {
        $data = Request()->param();
        !$data['ids'] && $this->error('参数错误');
        $re = Db::name('order')->where(['user_id'=>$this->shop_uid,'order_id'=>['in',$data['ids']]])->updata(['order_status'=>-1]);
        if ($re!==false) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 支付
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    function wxPay($order)
    {
        $cfg = Config::get('pay.wap');
        $PaySdk = new PaySdk($cfg);


        $arr = array(
            'out_trade_no'  => $order['out_trade_no'],
            'body'          => $order['body'],
            'total_fee'     => $order['order_money']*100,
            'mch_create_ip' => gethostbyname($_SERVER["SERVER_NAME"]),
            'device_info'   => 'iOS_WAP',
            'mch_app_name'  => '速冻在线',
            // 'mch_app_id'    => request()->domain(),
            // 'callback_url'  => request()->domain().url('order/orderdetail',['shop_id'=>$this->shop_id,'order_id'=>$order['order_id']])
            'mch_app_id'    => 'http://sdzx.tunnel.qydev.com',
            'callback_url'  => 'http://sdzx.tunnel.qydev.com'.url('order/orderdetail',['shop_id'=>$this->shop_id,'order_id'=>$order['order_id']])
        );

        $re = $PaySdk->submitOrderInfo($arr);
        return $re;
    }

    /**
     * 取消订单
     * @return [type] [description]
     */
    function cancel()
    {
        $data = Request()->param();
        !isset($data['order_id']) && $this->error('未选择订单');

        $order = Db::name('order')->where(['order_id'=>$data['order_id'],'user_id'=>$this->shop_uid])->find();
        !$order  && $this->error('订单不存在');

        $re = Db::name('order')->where(['order_id'=>$data['order_id'],'user_id'=>$this->shop_uid])->update(['order_status'=>5]);

        if ($re!==false) {
            Db::name('order_action')->insert([
                'user_id'          => $this->shop_uid,
                'order_id'         => $data['order_id'],
                'act_time'         => date('Y-m-d H:i:s'),
                'order_status'     => 5,
                'bop_order_status' => $order['order_status']
            ]);
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }
    }

    /**
     * 订单详情
     * @param string $value [description]
     */
    function orderDetail()
    {
        $data = Request()->param();
        !isset($data['order_id']) && $this->error('未选择订单');

        $list = Db::table('sdzx_order')->alias('o')
        ->join('sdzx_order_goods g', 'o.order_id=g.order_id')
        ->where("o.order_id={$data['order_id']}")
        ->select();

        // 订单合并
        $tmp_arr=[];
        foreach ($list as $k => $v) {
            if (!isset($tmp_arr['order_no'])) {
                $tmp_arr = [
                    'order_no'         => $v['order_no'],
                    'order_id'         => $v['order_id'],
                    'order_type'       => $v['order_type'],  //订单类型1：自主下单 2：代下单
                    'payment_type'     => $v['payment_type'], //支付类型  1：自主支付 2：管家支付
                    'user_id'          => $v['user_id'],
                    'user_name'        => $v['user_name'],
                    'agent_id'         => $v['agent_id'], //管家ID订单类型为 代下单 是才有
                    'agent_name'       => $v['agent_name'],
                    'create_time'      => $v['create_time'],
                    'receiver_name'    => $v['receiver_name'],
                    'receiver_mobile'  => $v['receiver_mobile'],
                    'receiver_address' => $v['receiver_address'],
                    'receiver_pcd'     => $v['receiver_pcd'],
                    'goods_money'      => $v['goods_money'],
                    'order_money'      => $v['order_money'],
                    'coupon_money'     => $v['coupon_money'],
                    'coupon_id'        => $v['coupon_id'],
                    'user_money'       => $v['user_money'],
                    'shipping_money'   => $v['shipping_money'],
                    'order_status'     => $v['order_status'],
                    'pay_platform'     => $v['pay_platform'],
                    'remarks'          => $v['remarks'],
                ];
            }
            $tmp_arr['list'][] = $v;
        }

       return $this->fetch('',['info'=>$tmp_arr]);
    }

    /**
    * 获取用户订单运费  之后可能跟用户等级有关
    * @return [type] [description]
    */
    public function shippingMoney($order_money=0)
    {
        $uid = $this->shop_uid;
        $free_shipping = Db::field('ul.free_shipping')
        ->table('sdzx_shop')->alias('s')
        ->join('sdzx_user_level ul','s.level=ul.level_id','left')
        ->where("s.user_id={$uid}")
        ->value('free_shipping');

        $return_arr = [
            'delivery_fee' => Config::get('sites.delivery_fee')?:0,
            'free_delivery_fee' => Config::get('sites.free_delivery_fee')?:0
        ];

        if ($free_shipping) {
            $return_arr['delivery_fee'] = 0;
        }else if ($order_money>0 && $return_arr['free_delivery_fee']>0 && $order_money>=$return_arr['free_delivery_fee']) {
            $return_arr['delivery_fee'] = 0;
        }
        
        return $return_arr;
    }

}
